#include"TimeWheel.h"
#include "Connection.h"
namespace wjc {

	TimeWheel::TimeWheel(Core* core, int wheelSize, int tickMs) :
		core_(core),
		wheelSize_(wheelSize),
		tickMs_(tickMs),
		timer_(new TimerChannel(core, tickMs)),
		wheel_(wheelSize_),
		cur_(0)
	{
		timer_->setOnTimerCallback(std::bind(&TimeWheel::advanceClock, this));

	}

	void TimeWheel::add(std::shared_ptr<Entry> entryPtr) {
		int index = (cur_ - 1 + wheelSize_) % wheelSize_;
		wheel_[index].push_back(entryPtr);
	}

	void TimeWheel::advanceClock() {
		wheel_[cur_].clear();
		cur_ = (++cur_) % wheelSize_;
	}

	Entry::Entry(std::weak_ptr<Connection> entry):entry_(entry) {

	}

	Entry::~Entry() {
		auto entry = entry_.lock();
		if (entry)
			entry->expired();
	}
}